<template>
  <el-drawer :title="title" :visible.sync="openDialog" size="70%" @closed="handleClose" :destroy-on-close="true" :wrapperClosable="false">
    <el-row type="flex" justify="center">
      <el-col :span="20">
        <el-steps :space="200" :active="activenum1" finish-status="success" :align-center="true" style="margin:0 0 50px 28px">
          <el-step title="基本信息"></el-step>
          <el-step title="商品规格"></el-step>
          <el-step title="商品详情"></el-step>
          <!-- <el-step title="完成"></el-step> -->
        </el-steps>
      </el-col>
    </el-row>
    <el-row type="flex" justify="center">
      <el-col :span="20">
        <el-form label-width="150px" :model="addGoodsInfo" ref="addFromRef" :rules="addFormRule" label-suffix="：">
          <el-tabs tab-position="left" style="height: 100%;" v-model="activenum2" :before-leave="leaveTab">
            <el-tab-pane label="基本信息" name="0">
              <el-form-item label="商品分类" prop="cartArr">
                <!-- 级联悬着器 -->
                <el-cascader v-model="addGoodsInfo.cartArr" :options="goodCates" :props="allcate" clearable></el-cascader>
              </el-form-item>
              <el-form-item label="商品品牌" prop="brand">
                <el-select v-model="addGoodsInfo.brand" placeholder="请选择品牌">
                  <el-option v-for="item in ppOption" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
              <el-form-item label="商品名称" prop="name">
                <el-input v-model="addGoodsInfo.name"></el-input>
              </el-form-item>
              <el-form-item label="商品关键词" prop="keyword">
                <el-input v-model="addGoodsInfo.keyword"></el-input>
                <p>商品关键词请用空格分隔；有两个功能，一是可以作为站内关键词查询，在前台搜索框输入关键词后，能够搜索到该商品；二是作为搜索引擎收录使用.</p>
              </el-form-item>
              <el-form-item label="商品标题" prop="title">
                <el-input v-model="addGoodsInfo.title"></el-input>
              </el-form-item>
              <el-form-item label="商品描述" prop="product_desc">
                <el-input type="textarea" v-model="addGoodsInfo.product_desc" autosize> </el-input>
              </el-form-item>
              <el-form-item label="商品货号" prop="code">
                <el-input v-model="addGoodsInfo.code" placeholder="请输入商品型号"></el-input>
              </el-form-item>
              <el-form-item label="服务范围" prop="area">
                <el-input v-model="addGoodsInfo.area" placeholder="请输入服务范围"></el-input>
              </el-form-item>
              <el-form-item label="质保期限" prop="exp_month">
                <el-input v-model.number="addGoodsInfo.exp_month" placeholder="请输入商品质保期限">
                 
                </el-input>
              </el-form-item>
              <el-form-item label="商品上架时间" prop="sale_start_time">
                <el-date-picker v-model="addGoodsInfo.sale_start_time" type="datetime" :picker-options="pickerOptionsStart" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间"></el-date-picker>
              </el-form-item>
              <el-form-item label="商品下架时间">
                <el-date-picker v-model="addGoodsInfo.sale_end_time" type="datetime" :picker-options="pickerOptionsEnd" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间"></el-date-picker>
              </el-form-item>
              <el-form-item label="商品推荐">
                <el-checkbox-group v-model="addGoodsInfo.featured">
                  <el-checkbox :label="1">新品</el-checkbox>
                  <el-checkbox :label="2">推荐</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <el-form-item label="服务保证">
                <el-checkbox-group v-model="addGoodsInfo.assurance">
                  <el-checkbox label="1">无忧退货</el-checkbox>
                  <el-checkbox label="2">快速退款</el-checkbox>
                  <el-checkbox label="3">免费包邮</el-checkbox>
                  <el-checkbox label="4">包安装</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <el-form-item label="商品轮播图" prop="imgs">
                <much-upload v-model="addGoodsInfo.imgs" :width="250" :isPx="isPxbtn"></much-upload>
              </el-form-item>
              <div class="btns">
                <el-button type="primary" @click="nextStep">下一步</el-button>
              </div>
            </el-tab-pane>
            <el-tab-pane label="商品规格" name="1">
              <el-button type="primary" @click="addGuige" style="margin:20px 0">添加商品规格</el-button>
              <el-table :data="goodsGuiGe" border style="width: 100%">
                <el-table-column prop="name" label="规格名称" width="200">
                  <template slot-scope="scope">
                    <el-input type="textarea" v-model="scope.row.name" size="mini"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="cost" label="成本价">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.cost" size="mini" oninput="value=value.replace(/[^0-9.]/g,'')"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="price" label="零售价">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.price" size="mini" oninput="value=value.replace(/[^0-9.]/g,'')"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="market" label="市场价">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.market" size="mini" oninput="value=value.replace(/[^0-9.]/g,'')"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="stock" label="商品库存">
                  <template slot-scope="scope">
                    <el-input v-model.number="scope.row.stock" size="mini"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="dw" label="商品单位">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.dw" size="mini"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="img" label="缩略图">
                  <template slot-scope="scope">
                    <!-- <pt-upload v-model="scope.row.img" :tip="false"></pt-upload> -->
                    <image-upload ref="upimg" v-model="scope.row.img" :tip="false" :width="100" :height="100" :showWidth="50" :showHeight="50" />
                  </template>
                </el-table-column>
                <el-table-column prop="pic" label="操作" width="120">
                  <template slot-scope="scope">
                    <el-button size="mini" type="success" icon="el-icon-arrow-up" @click="toTop(scope.row, scope.$index)"></el-button>
                    <el-popconfirm title="确定删除吗？" @onConfirm="delGuiGe(scope.row, scope.$index)">
                      <el-button size="mini" slot="reference" type="danger" icon="el-icon-delete"></el-button>
                    </el-popconfirm>
                  </template>
                </el-table-column>
              </el-table>
              <div class="btns">
                <el-button type="success" @click="shangStep">上一步</el-button>
                <el-button type="primary" @click="nextStep(1)">下一步</el-button>
              </div>
            </el-tab-pane>
            <el-tab-pane label="商品详情" name="2">
              <el-form-item label="商品详情图" prop="detail">
                <much-upload v-model="addGoodsInfo.detail" :width="200" :isPx="isPxbtn"></much-upload>
              </el-form-item>
              
              <div class="btns">
                <el-button type="success" @click="shangStep">上一步</el-button>
                <el-button type="primary" @click="save" :loading="loading">{{ loading ? '提交中 ...' : '完成' }}</el-button>
              </div>
            </el-tab-pane>
            <el-tab-pane label="完成" name="3">
              <div class="flex-ha">
                <i class="el-icon-circle-check" style="font-size:100px"></i>
              </div>

              <div class="btns">
                <el-button type="success" @click="shangStep">上一步</el-button>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-form>
      </el-col>
    </el-row>
  </el-drawer>
</template>

<script>

export default {

  data() {
    return {
      id: '',
      title: '新增商品信息',
      isPxbtn:false,
      ppOption: [],
      // activenum1: 0,
      activenum2: '0',
      openDialog: false,
      loading: false,
      addGoodsInfo: {
        cartArr: [],
        brand: '',
        name: '',
        keyword: '',
        title: '',
        product_desc: '',
        code: '',
        area: '',
        exp_month: '',
        sale_start_time: '',
        sale_end_time: '',
        featured: [],
        assurance: [],
        imgs: '',
        detail: ''
      },
      // 编辑器配置
      editorOption: {},
      addGuiGeItem: {
        name: '规格名称',
        cost: '100',
        market: '120',
        price: '150',
        stock: '99999',
        dw: '个',
        img: ''
      },
      dialogImageUrl: '',
      dialogVisible: false,
      goodsGuiGe: [],

      goodCates: [],
      allcate: {
        expandTrigger: 'hover',
        value: 'id',
        label: 'name',
        children: 'children'
      },
      pickerOptionsStart:{
        disabledDate: time => {
          return time.getTime() <= new Date().getTime()-1*24*60*59*1000
        }
      },
      pickerOptionsEnd: {
        disabledDate: time => {
          // 获取开始日期的 v-model 值并赋值给新定义的对象
          let beginDateVal = this.addGoodsInfo.sale_start_time;
          if (beginDateVal) {
              // 比较 距 1970 年 1 月 1 日之间的毫秒数：
              return time.getTime() < new Date(beginDateVal).getTime() - 1 * 24 * 60 * 60 * 1000
          }
        }
      },
      addFormRule: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'change' }
          // { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        cartArr: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
        // brand: [{ required: true, message: '请选择商品品牌', trigger: 'change' }],
        keyword: [{ required: true, message: '请输入关键词', trigger: 'change' }],
        title: [{ required: true, message: '请输入商品标题', trigger: 'change' }],
        product_desc: [{ required: true, message: '请输入商品描述', trigger: 'change' }],
        code: [{ required: true, message: '请输入商品货号', trigger: 'change' }],
        area: [{ required: true, message: '请输入服务范围', trigger: 'change' }],
        exp_month: [
          { required: true, message: '质保期限必填', trigger: 'change' },
          { type: 'number', message: '质保期限必须为数字值', trigger: 'change' },
        ],
        sale_start_time: [{ required: true, message: '请填写商品上架时间', trigger: 'change' }],
        imgs: [{ required: true, message: '请上传商品轮播图', trigger: 'change' }],
        detail: [{ required: true, message: '请上传商品详情图', trigger: 'change' }]

      }
      // 获取的商品分类数据
    }
  },
  created() {},
  computed: {
    queryData() {
      let obj = this.addGoodsInfo
      obj.featured = JSON.stringify(obj.featured)
      obj.assurance = JSON.stringify(obj.assurance)
      obj.min_price =  this.qujian(this.goodsGuiGe,'price').min
      obj.max_price =  this.qujian(this.goodsGuiGe,'price').max
      obj.specification = JSON.stringify(this.goodsGuiGe)
      obj.id = this.id
      obj.cate1 = obj.cartArr[0]
      obj.cate2 = obj.cartArr[1]
      return obj
    },
    activenum1() {
      return Number(this.activenum2)
    }
  },
  methods: {
    qujian(arr,price){
      let min = arr[0][price]
      let max = arr[0][price]
      arr.forEach(e => {
        if (e.price-0 <= min) {
          min = e.price
        }
        if (e.price-0 >= max) {
          max = e.price
        }
      })
      return {min:min,max:max}
    },
    init(val, goodCates, ppOption,type) {
      this.activenum2 = '0'
      console.log(this.activenum2);
      this.addGoodsInfo.detail = ''
      this.addGoodsInfo.imgs = ''
      this.goodCates = goodCates
      this.ppOption = ppOption
      this.openDialog = true
      if (val) {
        this.isPxbtn=false
        this.title = '修改商品信息'
        this.id = val.id
        this.$http.httpPost('products/productsDetail',{id:val.id}).then(res=>{
          let result = res.data
          if(result.code === 0){
            let data = result.data.data[0]
            data.assurance = JSON.parse(data.assurance)
            data.featured = JSON.parse(data.featured)
            data.sale_end_time = data.sale_end_time=='0000-00-00 00:00:00'?'':data.sale_end_time
            this.goodsGuiGe = JSON.parse(data.specification)
            this.addGoodsInfo = data
            this.addGoodsInfo.cartArr = [data.cate1, data.cate2]
             console.log(data, '会显示')
            if(type==2){
              this.title = '复制新建商品'
              this.id = ''
            }
          }  
        })
      } else {
        this.title = '新增商品信息'
        this.id = ''
        this.isPxbtn=true
        this.addGoodsInfo = this.$options.data().addGoodsInfo
        // Object.assign(this.$data, this.$options.data());
      }
    },
    addGuige() {
      let item = JSON.parse(JSON.stringify(this.addGuiGeItem))
      this.addGuiGeItem = item
      item.id = this.genID(10)
      this.goodsGuiGe.push(item)
    },
    genID(length){
      return Number(Math.random().toString().substr(3,length) + Date.now()).toString(36);
    },
    toTop(item, index) {
      let list = JSON.parse(JSON.stringify(this.goodsGuiGe))
      let first = list.splice(index, 1)
      this.goodsGuiGe = first.concat(list)
    },
    delGuiGe(item, index) {
      let list = JSON.parse(JSON.stringify(this.goodsGuiGe))
      list.splice(index, 1)
      this.goodsGuiGe = list
    },
    leaveTab(activeName, oldActiveName) {
      console.log(activeName, oldActiveName, '哈哈')
      if (oldActiveName == 1) {
        // if (this.goodsGuiGe.length < 1) {
        //   this.$message.error('必须设置商品高规格！')
        //   return false
        // } else {
        //   if (this.goodsGuiGe.some(e => e.img == '')) {
        //     this.$message.error('必须上传规格缩略图！')
        //     return false
        //   }
        // }
      } else if (oldActiveName == 2) {
        // if (this.addGoodsInfo.detail.length < 1) {
        //   this.$message.error('必须填写商品详情！')
        //   return false
        // }
      } else if (oldActiveName == 0) {
        // if (this.addGoodsInfo.cartArr.length < 1) {
        //   this.$message.error('请先选择商品分类！')
        //   return false
        // }
      }
    },
    nextStep(step) {
      this.activenum2 = Number(this.activenum2) + 1 + ''
    },
    shangStep() {
      this.activenum2 = Number(this.activenum2) - 1 + ''
    },
    handleClose() {
      if(this.$refs.addFromRef){
        this.$refs.addFromRef.resetFields()
      }
      this.addGoodsInfo = this.$options.data().addGoodsInfo
      this.goodsGuiGe = []
    },
    save() {
      if (this.goodsGuiGe.length < 1) {
        this.$message.error('必须设置商品规格！')
        return false
      } else {
        if (this.goodsGuiGe.some(e => e.img == '')) {
          this.$message.error('必须上传规格缩略图！')
          return false
        }
      }
      this.$refs.addFromRef.validate(valid => {
        if (valid) {
          this.loading = true
          setTimeout(()=>{
            this.loading = false
          },8000)
          this.$http.httpPost('/products/save', this.queryData).then(res => {
            if (res.data.code === 0) {
              this.activenum2 = '3'
              this.loading = false
              this.openDialog = false
              this.$emit('save')
              this.$operateTip()

            }else{
              this.loading = false
              this.$message.error(res.data.msg)
            }
          }).catch(re=>{
            this.loading = false
            this.$message.error('请求失败！可能是商品货号重复！')
            console.log(re,'cuowu');
            
          })
        } else {
          return this.$message.error('有必填项目未填写，请填写完后再提交！')
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.quill-editor {
  height: 400px;
}
.btns {
  height: 200px;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.addBox {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  .addInput {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    width: 30%;
    padding-bottom: 10px;
    span {
      width: 170px;
      text-align: right;
    }
  }
}
</style>
